package com.doge.calcalbum.business.sysalbum

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.doge.calcalbum.R
import com.doge.calcalbum.api.observeOnMain
import com.doge.calcalbum.api.subscribeOnIO
import com.doge.calcalbum.utils.*
import com.doge.calcalbum.widgets.Spanny
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
import kotlin.math.max

object SysEntryDeleteHelper {
    private const val spFolder = "behavior_settings"
    private const val spKey = "delete_origin"
    private const val STATE_UNSET = -1

    fun requireCheckDelete(context: Context, callback: (deleteOrigin: Boolean) -> Unit) {
        val delete = spReadInt(spKey, STATE_UNSET, spFolder)
        if (delete == STATE_UNSET) {
            SysEntryDeleteDialog.Builder(context)
                .setCallback(object : SysEntryDeleteDialog.Callback {
                    override fun onDelete() {
                        updateState(true)
                        callback(true)
                    }

                    override fun onKeep() {
                        updateState(false)
                        callback(false)
                    }
                }).create().show()
        } else {
            callback(delete == 1)
        }
    }

    fun getState(): Boolean = spReadInt(spKey, STATE_UNSET, spFolder) == 1

    fun updateState(delete: Boolean) {
        spWrite(spKey, if (delete) 1 else 0, spFolder)
    }
}


class SysEntryDeleteDialog private constructor(context: Context, theme: Int) :
    Dialog(context, theme) {
    private class Params {
        lateinit var mContext: Context
        var rootView: View? = null
        var canCancel = false
        var callback: Callback? = null
    }

    interface Callback {
        fun onKeep()
        fun onDelete()
    }

    private var p: Params? = null
    private var task: Disposable? = null

    override fun show() {
        super.show()
        val delete: TextView? = p?.rootView?.findViewById(R.id.delete)
        delete?.isEnabled = false
        delete?.setOnClickCallback {
            dismiss()
            p?.callback?.onDelete()
        }
        val keep = p?.rootView?.findViewById<TextView>(R.id.keep)
        keep?.setOnClickCallback {
            dismiss()
            p?.callback?.onKeep()
        }
        task?.dispose()
        task = Observable.interval(1, 1, TimeUnit.SECONDS)
            .subscribeOnIO()
            .observeOnMain()
            .doOnNext {
                val countdown = max(0, 3 - it)
                delete?.text =
                    if (countdown <= 0) getString(R.string.delete) else "${getString(R.string.delete)}($countdown)"
                delete?.isEnabled = countdown <= 0
            }
            .subscribe()
    }

    override fun dismiss() {
        super.dismiss()
        task?.dispose()
    }

    class Builder(context: Context) {
        private val p = Params()

        init {
            p.mContext = context
        }

        fun show() {
            create().show()
        }

        fun setCallback(
            callback: Callback
        ): Builder {
            p.callback = callback
            return this
        }

        fun create(): SysEntryDeleteDialog {
            val dialog = SysEntryDeleteDialog(
                p.mContext,
                R.style.Theme_Light_NoTitle_Dialog
            )

            val dip1 = (p.mContext.resources.displayMetrics.density + 0.5f).toInt()

            val window = dialog.window
            if (window != null) {
                window.decorView.setPadding(dip1 * 37, 0, dip1 * 37, 0)
                val lp = window.attributes
                lp.width = WindowManager.LayoutParams.MATCH_PARENT
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT
                window.attributes = lp
            }

            @SuppressLint("InflateParams") val view = LayoutInflater.from(p.mContext)
                .inflate(R.layout.dialog_delete_sys_entry, null)


            val message = view.findViewById<TextView>(R.id.message)
            message.text = Spanny().apply {
                append(getString(R.string.delete_sys_entry_desc))
                append(getString(R.string.delete_sys_entry_desc_tip), ForegroundColorSpan(getColor("#F56243")))
            }

            dialog.setContentView(view)
            dialog.setCanceledOnTouchOutside(p.canCancel)
            dialog.setCancelable(p.canCancel)
            p.rootView = view
            dialog.p = p
            return dialog
        }
    }
}